package com.example.qaplatform.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.*;

@RestController
@RequestMapping("/api/chat")
public class SpotExtraController {

    @Value("${ragflow.api.key}")
    private String ragflowApiKey;

    @Value("${ragflow.dataset.id}")
    private String datasetId;

    // 获取景点图片
    @GetMapping("/spotImage")
    public Map<String, Object> getSpotImage(@RequestParam("name") String name) {
        Map<String, Object> result = new HashMap<>();
        try {
            RestTemplate restTemplate = new RestTemplate();
            // 1. 查文档
            String docListUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents?page=1&page_size=3&keywords=" + name;
            HttpHeaders docHeaders = new HttpHeaders();
            docHeaders.set("Authorization", "Bearer " + ragflowApiKey);
            HttpEntity<String> docEntity = new HttpEntity<>(docHeaders);
            ResponseEntity<Map> docListResp = restTemplate.exchange(docListUrl, HttpMethod.GET, docEntity, Map.class);
            String docId = null;
            if (docListResp.getStatusCode() == HttpStatus.OK && docListResp.getBody() != null) {
                Object dataObj = docListResp.getBody().get("data");
                if (dataObj instanceof Map) {
                    Object docsObj = ((Map) dataObj).get("docs");
                    if (docsObj instanceof List && !((List) docsObj).isEmpty()) {
                        Object docObj = ((List) docsObj).get(0);
                        if (docObj instanceof Map) {
                            docId = ((Map) docObj).getOrDefault("id", "").toString();
                        }
                    }
                }
            }
            // 2. 查块，找图片块
            if (docId != null && !docId.isEmpty()) {
                String chunkListUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents/" + docId + "/chunks?page=1&page_size=5";
                HttpHeaders chunkHeaders = new HttpHeaders();
                chunkHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                HttpEntity<String> chunkEntity = new HttpEntity<>(chunkHeaders);
                ResponseEntity<Map> chunkListResp = restTemplate.exchange(chunkListUrl, HttpMethod.GET, chunkEntity, Map.class);
                if (chunkListResp.getStatusCode() == HttpStatus.OK && chunkListResp.getBody() != null) {
                    Object dataObj = chunkListResp.getBody().get("data");
                    if (dataObj instanceof Map) {
                        Object chunksObj = ((Map) dataObj).get("chunks");
                        if (chunksObj instanceof List) {
                            for (Object chunkObj : (List) chunksObj) {
                                if (chunkObj instanceof Map) {
                                    String imageId = ((Map) chunkObj).getOrDefault("image_id", "").toString();
                                    if (!imageId.isEmpty()) {
                                        result.put("url", "http://localhost/v1/document/image/" + imageId);
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            result.put("error", "图片检索异常: " + e.getMessage());
        }
        result.put("url", "");
        return result;
    }

    // 获取景点简介
    @GetMapping("/spotDesc")
    public Map<String, Object> getSpotDesc(@RequestParam("name") String name) {
        Map<String, Object> result = new HashMap<>();
        try {
            RestTemplate restTemplate = new RestTemplate();
            // 1. 查文档
            String docListUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents?page=1&page_size=3&keywords=" + name;
            HttpHeaders docHeaders = new HttpHeaders();
            docHeaders.set("Authorization", "Bearer " + ragflowApiKey);
            HttpEntity<String> docEntity = new HttpEntity<>(docHeaders);
            ResponseEntity<Map> docListResp = restTemplate.exchange(docListUrl, HttpMethod.GET, docEntity, Map.class);
            String docId = null;
            if (docListResp.getStatusCode() == HttpStatus.OK && docListResp.getBody() != null) {
                Object dataObj = docListResp.getBody().get("data");
                if (dataObj instanceof Map) {
                    Object docsObj = ((Map) dataObj).get("docs");
                    if (docsObj instanceof List && !((List) docsObj).isEmpty()) {
                        Object docObj = ((List) docsObj).get(0);
                        if (docObj instanceof Map) {
                            docId = ((Map) docObj).getOrDefault("id", "").toString();
                        }
                    }
                }
            }
            // 2. 查块，找文本块
            if (docId != null && !docId.isEmpty()) {
                String chunkListUrl = "http://localhost/api/v1/datasets/" + datasetId + "/documents/" + docId + "/chunks?page=1&page_size=5";
                HttpHeaders chunkHeaders = new HttpHeaders();
                chunkHeaders.set("Authorization", "Bearer " + ragflowApiKey);
                HttpEntity<String> chunkEntity = new HttpEntity<>(chunkHeaders);
                ResponseEntity<Map> chunkListResp = restTemplate.exchange(chunkListUrl, HttpMethod.GET, chunkEntity, Map.class);
                if (chunkListResp.getStatusCode() == HttpStatus.OK && chunkListResp.getBody() != null) {
                    Object dataObj = chunkListResp.getBody().get("data");
                    if (dataObj instanceof Map) {
                        Object chunksObj = ((Map) dataObj).get("chunks");
                        if (chunksObj instanceof List) {
                            for (Object chunkObj : (List) chunksObj) {
                                if (chunkObj instanceof Map) {
                                    String content = ((Map) chunkObj).getOrDefault("content", "").toString();
                                    if (!content.isEmpty()) {
                                        result.put("desc", content);
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            result.put("error", "简介检索异常: " + e.getMessage());
        }
        result.put("desc", "");
        return result;
    }
} 